package com.rm.zeyou.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rm.zeyou.constant.NumberConstants;
import com.rm.zeyou.constant.PayConstants;
import com.rm.zeyou.entity.MemberConfig;
import com.rm.zeyou.entity.User;
import com.rm.zeyou.entity.UserMemberOrder;
import com.rm.zeyou.exception.ErrorCodeException;
import com.rm.zeyou.exception.ErrorCodeExceptionEnum;
import com.rm.zeyou.mapper.MemberConfigMapper;
import com.rm.zeyou.mapper.UserMemberOrderMapper;
import com.rm.zeyou.pay.alipay.entity.AlipayEntity;
import com.rm.zeyou.pay.alipay.service.AlipayService;
import com.rm.zeyou.pay.wxpay.entity.WxPayEntity;
import com.rm.zeyou.pay.wxpay.service.WechatPayService;
import com.rm.zeyou.pay.wxpay.vo.SettleInfo;
import com.rm.zeyou.pay.wxpay.vo.WeChatCreateOrderVO;
import com.rm.zeyou.response.ApiRestResponse;
import com.rm.zeyou.service.UserMemberOrderService;
import com.rm.zeyou.util.check.CheckEmptyUtil;
import com.rm.zeyou.util.compute.ArithmeticUtil;
import com.rm.zeyou.util.random.RandomUtils;
import com.rm.zeyou.vo.request.OpenMemberVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户会员表 服务实现类
 * </p>
 *
 * @author YanYang
 * @since 2025-03-12 15:55:09
 */
@Service
public class UserMemberOrderServiceImpl extends ServiceImpl<UserMemberOrderMapper, UserMemberOrder> implements UserMemberOrderService {
    @Resource
    private MemberConfigMapper memberConfigMapper;
    @Resource
    private UserMemberOrderMapper userMemberOrderMapper;
    @Resource
    private WechatPayService wechatPayService;
    @Resource
    private WxPayEntity wxPayEntity;
    @Resource
    private AlipayService alipayService;
    @Resource
    private AlipayEntity alipayEntity;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse openMember(User user, OpenMemberVo openMemberVo) throws Exception {

        MemberConfig memberConfig = memberConfigMapper.selectById(openMemberVo.getMemberId());
        if (CheckEmptyUtil.isEmpty(memberConfig)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.MEMBER_CONFIG_ERROR);
        }

        String orderNo = RandomUtils.getOrderNo();
        // 创建订单
        UserMemberOrder insertUserMemberOrder = new UserMemberOrder();
        insertUserMemberOrder.setRechangeOrderNo(orderNo);
        insertUserMemberOrder.setUserId(user.getId());
        insertUserMemberOrder.setMemberId(openMemberVo.getMemberId());
        insertUserMemberOrder.setPayStatus(NumberConstants.ZERO_CONSTANTS);
        insertUserMemberOrder.setPayType(openMemberVo.getPayType());
        insertUserMemberOrder.setMemberType(memberConfig.getMemberType());
        insertUserMemberOrder.setEffectDay(memberConfig.getEffectDay());
        insertUserMemberOrder.setPayPrice(memberConfig.getMemberDiscountPrice());
        int insert = userMemberOrderMapper.insert(insertUserMemberOrder);
        if (insert == 0) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.CREATE_ORDER_FAIL);
        }

        // 拉起支付
        if (openMemberVo.getPayType().equals(PayConstants.WX)) {
            WeChatCreateOrderVO createOrderVO = new WeChatCreateOrderVO();
            if (openMemberVo.getWxType().equals(PayConstants.JSAPI_TYPE)) {
                if (CheckEmptyUtil.isEmpty(user.getOpenId())) {
                    throw new ErrorCodeException(ErrorCodeExceptionEnum.NOT_BIND_WX);
                }
                createOrderVO.setOpenId(user.getOpenId());
            }
            createOrderVO.setDescription("开通" + memberConfig.getMemberName());
            createOrderVO.setNotifyUrl(wxPayEntity.ProjectIP + "/api/wechat/rechargeNotify");
            createOrderVO.setOutTradeNo(orderNo);
            // WxPayTypeEnum.JSAPI_TYPE.getPayType()
            createOrderVO.setPayType(openMemberVo.getWxType());
            SettleInfo settleInfo = new SettleInfo();
            settleInfo.setProfit_sharing(false);
            createOrderVO.setSettleInfo(settleInfo);
            createOrderVO.setTotalPrice(ArithmeticUtil.mul(memberConfig.getMemberDiscountPrice(), new BigDecimal(100)));
            Map<String, String> order = wechatPayService.createOrder(createOrderVO);
            return ApiRestResponse.success(order);
        } else if (PayConstants.ZFB.equals(openMemberVo.getPayType())) {
            String pay = alipayService.pay(openMemberVo.getWxType(), "开通" + memberConfig.getMemberName(), orderNo, memberConfig.getMemberDiscountPrice().toString(), openMemberVo.getReturnUrl(), openMemberVo.getQuitUrl(), alipayEntity.getNotifyIp() + "/api/alipay/rechargeNotify");
            return ApiRestResponse.success(pay);
        } else {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.PAY_TYPE_ERROR);
        }

    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void closeUserMemberOrder() {
        List<UserMemberOrder> userMemberOrders = userMemberOrderMapper.selectList(new LambdaQueryWrapper<UserMemberOrder>()
                .eq(UserMemberOrder::getPayStatus, NumberConstants.ZERO_CONSTANTS));
        if (!CheckEmptyUtil.isEmpty(userMemberOrders)) {
            for (UserMemberOrder userMemberOrder : userMemberOrders) {
                if (new Date().after(DateUtil.offsetMinute(userMemberOrder.getCreateTime(), 3))) {
                    userMemberOrder.setPayStatus(NumberConstants.TWO_CONSTANTS);
                    userMemberOrderMapper.updateById(userMemberOrder);
                }
            }
            //List<Long> orderIds = userMemberOrders.stream().map(UserMemberOrder::getId).collect(Collectors.toList());
            //userMemberOrderMapper.updateOrderStatus(orderIds,NumberConstants.TWO_CONSTANTS);

        }

    }
}
